#include "process_pool.h"

// 创建子进程
int make_child(process_data_t *p_manage, int process_num)
{
    for (int i = 0; i < process_num; i ++)
    {
        int fds[2]; // 通信的管道
        socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
        
        pid_t pid = fork(); // 子进程pid
        if (pid == 0)
        {
            close(fds[1]);
            child_handle(fds[0]); // 子进程使用fds[0]和父进程通信
        }
        close(fds[0]);
        // 初始化子进程信息
        p_manage[i].pid = pid;
        p_manage[i].fd = fds[1]; // 父进程使用fds[1]和子进程通信
        p_manage[i].busy = 0;
#ifdef DEBUG
        printf("p_manage[%d].fd=%d\n",i,p_manage[i].fd);
#endif
    }
    
}

// 子进程任务
int child_handle(int fd)
{
    int new_fd; // 任务id
    char flag = 1;
    while (1)
    {
        // read(fd, &new_fd, sizeof(new_fd)); // 读管道
        int exit_flag;
        recv_fd(fd, &new_fd, &exit_flag);
        if (exit_flag)
        {
            printf("child %d will exit\n", getpid());
            exit(0);
        }
        printf("get task %d\n", new_fd);
        train_file(new_fd);
        printf("task %d finished!\n", new_fd);
        write(fd, &flag, sizeof(flag));// 通知父进程完成任务
        close(new_fd); // 在子进程中close，只会使new_fd的引用计数 -1
    }
}